<!-- "角色列表" -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRolesClick">添加角色</el-button>
      <el-table :data="rolesList" border style="width: 100%" stripe index>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row  :class="['v-tag-center','borderbottom',index1===0 ? 'bordertop':''] " :key="item1.id" v-for="(item1,index1) in scope.row.children">
              <el-col :span="5" >
                <el-tag  @close="removeById(scope.row,item1.id)" closable>{{item1.authName}} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row  :class="['v-tag-center',index2 ===0 ? '':'bordertop'] " :key="item2.id" v-for="(item2,index2) in item1.children">
                  <el-col :span="6" >
                    <el-tag  @close="removeById(scope.row,item2.id)" closable type="success">{{item2.authName}} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag @close="removeById(scope.row,item3.id)" closable type="warning" :key="item3.id" v-for="(item3) in item2.children">{{item3.authName}} </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          width="80">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template  slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="btnEditClick(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="small" @click="btnDeleteClick(scope.row)">删除</el-button>
              <el-button type="success" icon="el-icon-setting" size="small" @click="btnSettingClick(scope.row)">设置权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!-- 添加角色diaolog -->
    <el-dialog title="添加角色信息"  :visible.sync="dialogAddVisible"
      width="50%"
      @close="addDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="addForm" :rules="addFormRules"
        ref="addFormRef" label-width="120px">
        <el-form-item label="角色名称" prop="roleName" >
          <el-input v-model="addForm.roleName" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" >
          <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- dialog底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleDialogClick">确 定</el-button>
      </span>
    </el-dialog>
<!-- 编辑角色diaolog -->
    <el-dialog title="修改用户信息"  :visible.sync="dialogEditVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="editFrm" :rules="editFormRules"
        ref="editFormRef" label-width="120px">
        <el-form-item label="角色名称" prop="roleName" disabled>
          <el-input v-model="editFrm.roleName" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" >
          <el-input v-model="editFrm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- dialog底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserDialogClick">确 定</el-button>
      </span>
    </el-dialog>
<!-- 设置角色权限diaolog -->
    <el-dialog title="设置角色权限"  :visible.sync="dialogSettingRilesVisible"
      width="50%"
      @close="settingRoleDialogClosed">
      <!-- dialog主题区域 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys='dialogRolesDefaultKeys'
        :props="dialogRightsProps">
      </el-tree>
      <!-- dialog底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSettingRilesVisible = false">取 消</el-button>
        <el-button type="primary" @click="settingRoleUserDialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      rolesList: [],
      dialogAddVisible: false,
      dialogEditVisible: false,
      dialogSettingRilesVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '角色名称自长度在1-10之间',
            trigger: 'blur'
          }
        ]
      },
      editFrm: {},
      editFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '角色长度在1-10之间',
            trigger: 'blur'
          }
        ]
      },
      rightsList: [],
      dialogRightsProps: {
        label: 'authName',
        children: 'children',
        disabled: false,
        isLeaf: true
      },
      dialogRolesDefaultKeys: [],
      roleID: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      let { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }
      this.rolesList = res.data
    },
    // 根据id删除标签权限
    async removeById (row, id) {
      const result = await this.$confirm('是否删除该用户权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (result !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // this.getRolesList()
      row.children = res.data
    },
    // 删除角色点击事件
    async btnDeleteClick (roles) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      let { data: res } = await this.$http.delete('roles/' + roles.id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 设置权限点击事件
    async btnSettingClick (roles) {
      this.roleID = roles.id
      let { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      this.getLeafKeys(roles, this.dialogRolesDefaultKeys)
      this.dialogSettingRilesVisible = true
    },
    // 添加角色事件
    addRolesClick () {
      this.dialogAddVisible = true
    },
    // 添加角色dialog关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色dialog确定事件
    addRoleDialogClick () {
      this.$refs.addFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        let { data: res } = await this.$http.post('roles', {
          roleName: this.addForm.roleName,
          roleDesc: this.addForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败!')
          return
        }
        this.$message.success('添加角色成功!')
        this.dialogVisible = false
        this.getUsersList()
      })
    },
    // 编辑点击事件
    async btnEditClick (roles) {
      let { data: res } = await this.$http.get('roles/' + roles.id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.editFrm = res.data
      this.dialogEditVisible = true
    },
    // 编辑角色dialog关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑角色dialog确定事件
    editUserDialogClick () {
      this.$refs.editFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        let { data: res } = await this.$http.put('roles/' + this.editFrm.roleId, {
          roleName: this.editFrm.roleName,
          roleDesc: this.editFrm.roleDesc
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失败')
        }
        this.$message.success('更新角色成功!')
        this.getRolesList()
        this.dialogEditVisible = false
      })
    },
    // 设置角色权限dialog关闭事件
    settingRoleDialogClosed () {
      this.dialogRolesDefaultKeys = []
    },
    // 设置角色权限dialog确定事件
    settingRoleUserDialogClick () {
      this.getAllSelectRights()
    },
    // 获取当前角色拥有权限
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 得到所有选中权限ID数组集合
    async getAllSelectRights () {
      const allRight = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const allRightsStr = allRight.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleID}/rights`, {
        rids: allRightsStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.dialogSettingRilesVisible = false
    }
  }
}

</script>
<style lang='less' scoped>
.el-tag{
  margin: 10px;
}
.bordertop{
  border-top: 1px solid  #eeeeee ;
}
.borderbottom{
    border-bottom: 1px solid  #eeeeee ;
}
.v-tag-center{
  display: flex;
  align-items: center;
}
</style>
